package com.zhanglijie.improve.atomic.two;

import com.zhanglijie.improve.atomic.domain.Person;
import com.zhanglijie.improve.atomic.two.CommonAtomic;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/6 0006 1:40
 */
public class TestCommonAtomic {
    public static void main(String[] args) {
        testOne();
        System.out.println("=====================");
        testTwo();
        System.out.println("=====================");
        testThree();

    }

    /**
     * 解决aba问题
     */
    private static void testThree() {
        Person zhangsan = new Person(1, "zhangsan");
        Person lise = new Person(2, "lise");
        CommonAtomic<Person> atomic = new CommonAtomic<Person>(zhangsan,0);
        new Thread(()->{
            try {
                Thread.sleep(1000);
            }catch (Exception e){}
            boolean b = atomic.compareAndSet(zhangsan, lise, 0, 1);

            System.out.println(Thread.currentThread().getName()+"设置 "+b+" 版本 ,"+atomic.getVersion()+" 值"+atomic.getValue());
        },"thread-1").start();

        new Thread(()->{

            Person wanger = new Person(4, "wanger");
            int version = atomic.getVersion();
            try {
                Thread.sleep(3000);
            }catch (Exception e){}
            boolean  b= atomic.compareAndSet(lise, wanger, version, 1);
            System.out.println(Thread.currentThread().getName()+"设置 "+b+" 版本 ,"+atomic.getVersion()+" 值"+atomic.getValue());
        },"thread-2").start();
    }

    /**
     * aba问题演示
     */
    private static void testTwo() {
        Person zhangsan = new Person(1, "zhangsan");
        Person lise = new Person(2, "lise");
        CommonAtomic<Person> atomic = new CommonAtomic<Person>(zhangsan);
        atomic.compareAndSet(zhangsan,lise);
        atomic.compareAndSet(lise,zhangsan);
        boolean b = atomic.compareAndSet(zhangsan, lise);
        System.out.println("aba 设置是否成功"+b+" ,当前最新值+"+atomic.getValue());//lise

    }

    /**
     * cas 操作
     */
    private static void testOne() {
        Person zhangsan = new Person(1, "zhangsan");
        Person lise = new Person(2, "lise");
        CommonAtomic<Person> atomic = new CommonAtomic<Person>(zhangsan);
        atomic.compareAndSet(zhangsan,lise);

        System.out.println(atomic.getValue());

    }
}
